<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <!-- 提示区 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 进度条 -->

      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"> </el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab标签页 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :before-leave="beforeLeave"
          v-model="activeIndex"
          :tab-position="'left'"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="categoriesList"
                @change="handleChange"
                clearable
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                  children: 'children',
                }"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染参数表单 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item2"
                  v-for="(item2, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="uploadHeaders"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor">
            </quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" @click="addGoods" class="addBtn"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 上传图片预览的对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="setUploadDialogVisible"
      width="50%"
    >
      <img :src="picUrl" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  created() {
    this.getCategoriesList()
  },
  data() {
    let checkCounts = (rules, val, cb) => {
      if (val <= 0) {
        return cb(new Error('请输入大于0的数字'))
      }
      return cb(new Error('请输入数字'))
    }

    return {
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        //商品分类数组 保存选中的商品分类id值
        goods_cat: [],
        pics: [],
        //保存商品介绍
        goods_introduce: '',
        //保存动态参数和静态属性
        attrs: [],
      },

      addRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur',
          },
        ],

        goods_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur',
          },

          { validator: checkCounts, trigger: 'blur' },
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur',
          },

          { validator: checkCounts, trigger: 'blur' },
          {},
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur',
          },
          { validator: checkCounts, trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
      },
      //商品分类数据
      categoriesList: [],
      //动态参数数据
      manyTabData: [],
      //静态参数数据
      onlyTabData: [],
      //上传图片的url
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      setUploadDialogVisible: false,
      //上传图片的访问路径
      picUrl: '',
      editorOption: [],
      content: '',
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length > 0) {
        return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
      }
      return null
    },
  },

  methods: {
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.info('获取参数列表失败')
      }

      this.categoriesList = res.data
      console.log(this.categoriesList)
    },

    //当级联选中的选项值发生改变时触发
    handleChange() {
      console.log(this.addForm.goods_cat)
      console.log('ok')
    },
    //切换页签之前触发
    beforeLeave(activeName, oldActiveName) {
      //console.log('目前处在：' + activeName + ',历史处在：' + oldActiveName)
      if (oldActiveName === '0' && this.addForm.goods_cat.length < 2) {
        this.$message.info('请先选择基本信息中的商品分类')
        return false
      }
    },
    //当页签被点击时触发
    async tabClicked() {
      //这里默认写死查询参数为many
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many',
            },
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取商品参数失败')
        }

        //data中attr_vals数据是一个以字符串分割的数据
        //我们需要将其转换成数组方便渲染

        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
        console.log(res.data)
        this.manyTabData = res.data
      }

      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only',
            },
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取商品参数失败')
        }

        this.onlyTabData = res.data
        console.log(this.onlyTabData)
      }
    },
    //处理上传图片预览效果
    handlePreview(fileInfo) {
      //console.log(fileInfo)
      this.picUrl = fileInfo.response.data.url
      this.setUploadDialogVisible = true
    },
    //处理移除图片时业务逻辑
    handleRemove(fileInfo) {
      //console.log(fileInfo.response.data.tmp_path)
      //获取移除的图片的临时路径
      const tempPath = fileInfo.response.data.tmp_path
      //从pics数组中找到该临时路径对应的索引值
      const index = this.addForm.pics.findIndex((item) => {
        item.pic === tempPath
      })
      //调用pics数组中splice方法移除该图片
      this.addForm.pics.splice(index, 1)
      //console.log(this.addForm.pics)
    },
    //处理图片上传成功的钩子
    handleSuccess(resp) {
      //拼接图片信息对象
      const picInfo = { pic: resp.data.tmp_path }
      //将图片信息添加到pics数组中
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },
    //添加商品
    addGoods() {
      //添加商品之前先拿到表单的引用做预验证
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请检查必填项是否填写')

        //预验证通过后 处理即将要发起请求的参数
        //由于我们的参数有双向绑定
        //级联选择器双向绑定了goods_cat中的分类id,接收的是数组
        //API接收该属性是字符串，一旦改变就会报错
        //所以我们使用loadsh中的深拷贝方法
        //将数据独立出来方便我们做处理 而不影响其他

        const form = _.cloneDeep(this.addForm)

        form.goods_cat = form.goods_cat.join(',')
        console.log(form.goods_cat)
        //处理动态参数和静态属性到addForm.attrs数组中
        //1处理动态参数
        this.manyTabData.forEach((item) => {
          const manyInfo = {
            attr_id: item.attr_id,
            //渲染组件时需要将attr_vals的字符串值处理成数组
            //现在要发起请求需要重新还原成字符串格式
            attr_value: item.attr_vals.join(' '),
          }
          //处理好后的数据添加到attrs数组中
          this.addForm.attrs.push(manyInfo)
        })
        //2处理静态属性
        this.onlyTabData.forEach((item) => {
          const onlyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }

          this.addForm.attrs.push(onlyInfo)
        })

        //我们最终是要发送深拷贝后form
        //所以将addForm.attrs值给form.attrs
        form.attrs = _.cloneDeep(this.addForm.attrs)

        //发起请求添加商品
        //商品名称必须唯一
        const { data: res } = await this.$http.post('goods', form)

        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }

        this.$message.success('添加商品成功')
        //添加成功后跳转商品列表页面
        this.$router.push('/goods')
      })
    },
  },
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.addBtn {
  margin-top: 20px;
}
</style>